import 'package:edu/pages/signin/welcome/welcome_page.dart';
import 'package:edu/utils/database_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:edu/constants/app_strings.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/app_preferences.dart';
import 'package:edu/utils/app_router.dart';
import 'package:edu/utils/app_theme.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:media_kit/media_kit.dart';

void main() async {
  // 确保初始化完成
  WidgetsFlutterBinding.ensureInitialized();
  // 初始化媒体处理相关工具库
  MediaKit.ensureInitialized();

  // 初始化主题
  await AppTheme.shared.init();
  // 初始化欢迎页面配置
  await AppPreferences.shared.init();
  // 初始化数据获取器
  await DataFetcher.shared.init();
  // 加载用户信息
  await AccountInfo.shared.init();
  // 初始化数据库
  await DatabaseHelper.shared.init();

  // 运行apps
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late final MaterialApp _mainApp;

  bool _showMainWidget = false;

  @override
  void initState() {
    super.initState();

    // 创建路由
    final router = AppRouter.shared.router;

    // 创建MaterialApp
    _mainApp = MaterialApp.router(
      title: AppStrings.appName,
      theme: AppTheme.shared.currentTheme,
      debugShowCheckedModeBanner: false,
      routerDelegate: router.routerDelegate,
      routeInformationParser: router.routeInformationParser,
      routeInformationProvider: router.routeInformationProvider,
      builder: EasyLoading.init(),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 判断是否是第一次运行
    if (AppPreferences.shared.isFirstRun) {
      if (_showMainWidget) {
        // 显示主页
        return _mainApp;
      } else {
        // 显示欢迎页面
        _showMainWidget = true;
        return MaterialApp(
          // 设置标题
          title: AppStrings.appName,
          // 设置主题
          theme: AppTheme.shared.currentTheme,
          // 去掉debug标签
          debugShowCheckedModeBanner: false,
          // home: WelcomePage(),
          home: WelcomePage(
            // 跳转
            skipAction: () {
              setState(() {
                _showMainWidget = true;
              });
            },
          ),
        );
      }
    } else {
      // 显示主页
      return _mainApp;
    }
  }
}
